import 'dart:async';
import 'dart:io';

import 'package:flutter/material.dart';
// import 'package:flutter_aliplayer/flutter_alilistplayer.dart';
// import 'package:flutter_aliplayer/flutter_aliplayer_factory.dart';
import 'package:flutter_smart_dialog/flutter_smart_dialog.dart';
import 'package:lcapp/api/interface/home_api.dart';
import 'package:lcapp/api/request/response_data.dart';
import 'package:lcapp/basic/local_info.dart';
import 'package:lcapp/basic/user_info.dart';
import 'package:lcapp/data/lc_video_data_entity.dart';
import 'package:lcapp/model/event/event_bus.dart';
import 'package:lcapp/model/login/login_util.dart';
import 'package:lcapp/model/toast/toast.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:lcapp/page/home/home_new_video_item.dart';

import 'home_video_item.dart';

class HomeVideoPage extends StatefulWidget {
  const HomeVideoPage({Key? key}) : super(key: key);

  @override
  _HomeVideoPageState createState() => _HomeVideoPageState();
}

class _HomeVideoPageState extends State<HomeVideoPage> with AutomaticKeepAliveClientMixin {
  PageController? pageController;
  int pageNum = 1;
  int pageSize = 10;
  List<LcVideoDataEntity> lcVideos = [];
  StreamSubscription? _streamSubscription;
  StreamSubscription? loginSub;


  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    loginSub = eventBus.on<LoginState>().listen((event) {
      if(AsrLocalInfo.token==null){
        // pageController.animateTo(0, duration:  const Duration(microseconds: 100), curve: Curves.linear);
        pageNum=1;
        getVideos();
      }else{
        pageNum++;
        getVideos();
      }
    });
    pageController = PageController();
    _streamSubscription = eventBus.on<FabuState>().listen((event) {
      if (event.type == 0) {
        pageNum=1;
        getVideos();
      }
    });
    getVideos(isShowLoading: true);
  }

  getVideos({bool isShowLoading = false})async{

    if(isShowLoading){
      showLoading();
    }
    ResponseData res = await HomeAPI.getVideos(pageNum,pageSize);
    if(isShowLoading){
      hideLoading();
    }
    if(res.code==200){
      List arr = res.data??[];
      if(pageNum==1){
        lcVideos.clear();
      }
      for (var element in arr) {
        LcVideoDataEntity entity = LcVideoDataEntity().fromJson(element);
        print('address=======${entity.address}' );
        lcVideos.add(entity);
      }
    }
    if(mounted){setState(() {
    });}

  }

  @override
  void dispose() {
    // TODO: implement dispose
    super.dispose();
    _streamSubscription?.cancel();
    loginSub?.cancel();
  }

  @override
  Widget build(BuildContext context) {
    return lcVideos.isEmpty?Container(
      child: Center(
        child: GestureDetector(
          onTap: (){
            pageNum=1;
            getVideos(isShowLoading: true);
          },
          child: const Text('点击加载',style:  TextStyle(
              color: Colors.white
          ),),
        ),
      ),
    ):
    RefreshIndicator(
      onRefresh: ()async{
        pageNum = 1;
        getVideos();
      },
      child: PageView.builder(
        controller: pageController,
        scrollDirection: Axis.vertical,
        itemCount: lcVideos.length,
        onPageChanged: (index){
          if(AsrLocalInfo.token==null&&lcVideos.length==10&&index == 9){
            showToast('登录后浏览更多货源视频');
            Future.delayed(const Duration(milliseconds: 2000),(){
              SmartDialog.dismiss();
              eventBus.fire(HomeChangeIndex(canPlay:false));
              LoginUtil.login();
            });
            return;
          }
          if(userInfo.vip==0&&lcVideos.length==30&&index == 29){
            showToast('开通会员为您匹配更多货源视频');
            Future.delayed(const Duration(milliseconds: 2000),(){
              SmartDialog.dismiss();
              Navigator.of(context).pushNamed("MinVipPage").then((value){
                pageNum++;
                getVideos();
              });
            });
            return;
          }
          if(index==lcVideos.length-1&&index>0){
            pageNum++;
            getVideos();
          }
        },
        itemBuilder: (context, index) {
          return Platform.isIOS ?  HomeVideoItem(2,entity: lcVideos[index],videos: lcVideos, clickFun: (){},):HomeVideoItem(2,entity: lcVideos[index],videos: lcVideos, clickFun: (){},);
        },
      ),
    );
  }


  @override
  // TODO: implement wantKeepAlive
  bool get wantKeepAlive => true;
}
